<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 3/26/24
 * Time: 6:32 PM
 */

namespace app\job;

use app\common\service\ContentService;
use think\queue\Job;
use think\facade\Log;
use app\common\model\book\Book;
use app\common\model\book\Chapter;

class CopyBookJob
{
    public function fire(Job $job, $data)
    {

        // 检查书籍是否复制成功
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if (!$isJobStillNeedToBeDone) {
            $job->delete();

            return;
        }

        try {
            $copyBook = Book::where('id', $data['copy_id'])->findOrEmpty();
            if ($copyBook->isEmpty()) {
                throw new \Exception('克隆的书籍不存在');
            }
            // 获取克隆章节信息
            $copyChapters = Chapter::suffix(getSuffix($data['copy_id']))
                ->where('book_id', $data['copy_id'])
                ->order('chapter_order', 'asc')
                ->select();
            if ($copyChapters->isEmpty()) {
                throw new \Exception('克隆的书籍章节信息不存在');
            }

            Log::info('====>开始克隆书籍章节信息到OSS');

            foreach ($copyChapters as $copyChapter) {

                $chapter = Chapter::suffix(getSuffix($data['id']));

                $chapter->siteid        = $copyChapter->siteid;
                $chapter->sourceid      = $copyChapter->sourceid;
                $chapter->sourcecid     = $copyChapter->sourcecid;
                $chapter->chapter_name  = $copyChapter->chapter_name;
                $chapter->checkname     = $copyChapter->checkname;
                $chapter->book_id       = $data['id'];
                $chapter->book_name     = $copyChapter->book_name;
                $chapter->word_count    = $copyChapter->word_count;
                $chapter->chapter_order = $copyChapter->chapter_order;
                $chapter->summary       = $copyChapter->summary;
                $chapter->checked       = $copyChapter->checked;
                $chapter->is_vip        = $copyChapter->is_vip;
                $chapter->price         = $copyChapter->price;
                $chapter->chapterprice  = $copyChapter->chapterprice;
                $chapter->reltopic      = $copyChapter->reltopic;
                $chapter->free_time     = $copyChapter->free_time;
                $chapter->check_remark  = $copyChapter->check_remark;
                $chapter->create_time   = time();
                $chapter->update_time   = time();
                $chapter->pub_time      = $copyChapter->pub_time;
                $chapter->authtime      = $copyChapter->authtime;

                if (!$chapter->save()) {
                    continue;
                }

                // 上传章节信息到OSS
                $copyContent = ContentService::getContentUrl($copyChapter->content_url, $copyBook->id, $copyChapter->chapter_id);
                if (!$copyContent) {
                    continue;
                }
                $contentUrl           = ContentService::uploadContent($data['id'], $chapter->chapter_id, $copyContent);
                $chapter->content_url = $contentUrl;
                if (!$chapter->save()) {
                    continue;
                }
                Log::info('====>克隆书籍章节：' . $copyChapter->chapter_id . '克隆完成');
            }

        } catch (\Exception $exception) {
            Log::error('队列任务克隆书籍：' . $data['copy_id'] . '执行失败：' . $exception->getMessage());

            $book = Book::where('id', $data['id'])->findOrEmpty();
            $book->delete();
        }

        Log::info('====>克隆书籍任务执行完成');
        $job->delete();  // 执行失败，删除任务
    }


    /**
     * todo(判断书籍是否复制失败，已经不再需要执行了)
     *
     * @param $data
     * @return bool
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data)
    {
        if (Book::where('id', $data['id'])->findOrEmpty()->isEmpty()) {

            return false;
        }

        return true;
    }
}
